package cn.cupk.corporateshuttlemanagesystem.controller;

import cn.cupk.corporateshuttlemanagesystem.mapper.UserMapper;
import cn.cupk.corporateshuttlemanagesystem.pojo.Users;
import cn.cupk.corporateshuttlemanagesystem.result.PageResult;
import cn.cupk.corporateshuttlemanagesystem.result.RequestParams;
import cn.cupk.corporateshuttlemanagesystem.result.Result;
import cn.cupk.corporateshuttlemanagesystem.service.UserService;
import cn.cupk.corporateshuttlemanagesystem.utils.JwtUtil;
import cn.cupk.corporateshuttlemanagesystem.utils.Md5Util;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private UserService userService;
    @Autowired
    private UserMapper userMapper;

    @PostMapping("/register")
    public Result register(@RequestBody Users user) {

        //校验
        if (userService.findUserByUsername(user.getUsername()) != null) {
            return Result.error("用户名已存在");
        }
        if (userService.findCompanyByName(user.getCompanyName()) == null) {
            return Result.error("该公司未加入本系统");
        }
        //添加用户
        userService.addUser(user);

        return Result.success("注册成功");
    }

    @PostMapping("/login")
    public Result login(@RequestBody Users users) {
        String username = users.getUsername();
        String password = users.getPassword();
        Users user = userService.findUserByUsername(username);
        if (user == null) {
            return Result.error("用户不存在");
        }
        if (user.getIsactive().equals("off")){
            return Result.error("该用户已被禁用，请联系管理员");
        }
        if (user.getPassword().equals(Md5Util.getMD5String(password)) || user.getPassword().equals(password)) {
                Map<String, Object> claims = new HashMap<>();
                claims.put("id", users.getUserId());
                claims.put("username", users.getUsername());
                String token = JwtUtil.genToken(claims);
                //把token存储到redis中
                ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
                operations.set(token,token,1, TimeUnit.HOURS);
                return Result.success(token);

        }
        return Result.error("密码错误");
    }

    @PostMapping("/updateuser")
    public Result updateUser(@RequestBody Users user) {
        Users userByUsername = userService.findUserByUsername(user.getUsername());
        //校验
        if (userByUsername != null && userByUsername.getUserId() != user.getUserId()) {
            return Result.error("用户名已存在");
        }
        if (userService.findCompanyByName(user.getCompanyName()) == null) {
            return Result.error("该公司未加入本系统");
        }
        userService.updateUser(user);
        return Result.success("用户信息修改成功");
    }

    @GetMapping("/finduserByid")
    public Result findUserByUserId(int userId) {
        Users user = userService.findUserById(userId);
        if (user == null) {
            return Result.error("用户未找到");
        }
        return Result.success(user);
    }


    @PostMapping("/list")
    public Result<Object> list(@RequestBody RequestParams<Users> params) {
        //获取用户信息
        Integer userId = params.getData().getUserId();
        Users userById = userMapper.findUserById(userId);
        //设置公司id
        params.getData().setCompanyId(userById.getCompanyId());
        //分页查询
        Page<Object> page = PageHelper.startPage(params.getPageNum(), params.getPageSize());
        List<Users> page1 = userMapper.page(params.getData());

        return Result.ok(new PageResult<>(page.getTotal(), page1));
    }

    @PostMapping("/add")
    public Result add(@RequestBody Users user) {
        //校验
        if (userService.findUserByUsername(user.getUsername()) != null) {
            return Result.error("用户名已存在");
        }
        if (userService.findCompanyByName(getCompanyName(user.getCompanyId())) == null) {
            return Result.error("该公司未加入本系统");
        }
        //添加用户
        userMapper.addUser(user);

        return Result.success("新增成功");
    }

    @PostMapping("/update")
    public Result update(@RequestBody Users user) {
        Users userByUsername = userService.findUserByUsername(user.getUsername());
        //校验
//        if (userByUsername == null && userByUsername.getUserId() != user.getUserId()) {
//            return Result.error("用户名已存在");
//        }
        if (userService.findCompanyByName(getCompanyName(user.getCompanyId())) == null) {
            return Result.error("该公司未加入本系统");
        }
        user.setCompanyId(userService.findCompanyByName(getCompanyName(user.getCompanyId())).getCompanyId());
        userMapper.updateUser(user);
        return Result.ok("修改成功");
    }


    private String getCompanyName(Integer companyId) {
        switch (companyId) {
            case 1:
                return "公司A";
            case 2:
                return "公司B";
            case 3:
                return "公司C";
            default:
                return null;
        }

    }


}
